package com.jiegui.common.utils;

import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;


/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
public class JsonUtils {
    private static final ObjectMapper JSON = new ObjectMapper();

    static {
        JSON.setSerializationInclusion(Include.NON_NULL);
        JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
    }

    public static String toJson(Object obj) {
        try {
            return JSON.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 反序列化
     *
     * @param jsonText
     * @return
     */
    public static final Object parseObject(String jsonText) {
        return com.alibaba.fastjson.JSON.parse(jsonText);
    }

    /**
     * 反序列化指定对象
     *
     * @param jsonText
     * @param classz
     * @return
     */
    public static final <T> T parseObject(String jsonText, Class <T> classz) {
        return com.alibaba.fastjson.JSON.parseObject(jsonText, classz, Feature.OrderedField);
    }


    /**
     * 对象序列化
     *
     * @param object
     * @return
     */
    public static final String toJSONString(Object object) {
        return com.alibaba.fastjson.JSON.toJSONString(object, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.DisableCircularReferenceDetect);
    }

}
